package util;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import javax.swing.Timer;
import model.Purchase;

public class SeatHolder {

    // movieSectionId + seatNo as the key
    private static HashMap<String, SeatHolder> m_mapSeatHolders = new HashMap<String, SeatHolder>();
    private Purchase m_purchase;
    private Timer m_timer;
    private static final int holdTime = 5 * 60 * 1000;

    public static SeatHolder getSeatHolder(String movieSectionId, String seatNo) {
        String key = movieSectionId + seatNo;
        return m_mapSeatHolders.get(key);
    }

    public SeatHolder(Purchase newPurchase) {
        m_purchase = newPurchase;
        m_timer = new Timer(holdTime, timerListener);
    }

    public void startHolding() throws Exception {
        boolean success = HibernateUtil.insert(m_purchase);
        if (success == false) {
            throw new Exception("Fail to book the seats. Please try again. ");
        }
        String key = m_purchase.getPurchaseId().getMovieSectionId() + m_purchase.getPurchaseId().getSeatNo();
        m_mapSeatHolders.put(key, this);
        if (!m_timer.isRunning()) {
            m_timer.start();
        }
    }

    public void paidWithMoney() {
        if (m_timer.isRunning()) {
            m_timer.stop();
        }
        String key = m_purchase.getPurchaseId().getMovieSectionId() + m_purchase.getPurchaseId().getSeatNo();
        m_mapSeatHolders.remove(key);
        m_purchase.setRemark("");
        HibernateUtil.update(m_purchase);
    }

    public void paidWithLoyalty() {
        if (m_timer.isRunning()) {
            m_timer.stop();
        }
        String key = m_purchase.getPurchaseId().getMovieSectionId() + m_purchase.getPurchaseId().getSeatNo();
        m_mapSeatHolders.remove(key);
        m_purchase.setRemark("Paid with loyalty, cannot refund");
        HibernateUtil.update(m_purchase);
    }
    /*
     * timer listener
     */
    private ActionListener timerListener = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            if (m_timer.isRunning()) {
                m_timer.stop();
            }
            String key = m_purchase.getPurchaseId().getMovieSectionId() + m_purchase.getPurchaseId().getSeatNo();
            m_mapSeatHolders.remove(key);
            HibernateUtil.delete(m_purchase);
        }
    };
}
